package com.ruoyi.know.service;

import com.github.houbb.sensitive.word.bs.SensitiveWordBs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class SensitiveWordService {

    @Autowired
    private SensitiveWordBs sensitiveWordBs;

    /**
     * 检测是否包含敏感词
     */
    public boolean containsSensitive(String text) {
        return sensitiveWordBs.contains(text);
    }

    /**
     * 替换敏感词
     */
    public String replaceSensitive(String text) {
        return sensitiveWordBs.replace(text);
    }

    /**
     * 获取文本中的所有敏感词
     */
    public List<String> findAllSensitive(String text) {
        return sensitiveWordBs.findAll(text);
    }

    /**
     * 自定义提交内容中图片路径的错误覆盖
     */
    public String replaceWithImgTag(String text) {
        if(text == null || text.isEmpty()){
            return text;
        }
        // 定义正则表达式来匹配 <img> 标签
        Pattern imgPattern = Pattern.compile("<img[^>]*>");
        Matcher imgMatcher = imgPattern.matcher(text);
        // 存储 <img> 标签及其对应的占位符
        Map<String, String> imgMapping = new HashMap<>();
        int index = 0;
        while (imgMatcher.find()) {
            String imgTag = imgMatcher.group();
            String placeholder = "__IMG_PLACEHOLDER_" + index + "__";
            imgMapping.put(placeholder, imgTag);
            text = text.replace(imgTag, placeholder);
            index++;
        }

        //  如果存在
        if(index > 0){
            // 对除img标签外的其他内容进行敏感词检测
            text = sensitiveWordBs.replace(text);
            // 恢复 <img> 标签
            for (Map.Entry<String, String> entry : imgMapping.entrySet()) {
                text = text.replace(entry.getKey(), entry.getValue());
            }
        }

        return text;
    }
}
